import {Component, ViewEncapsulation, ViewChild, Input} from '@angular/core';
import {IdeaService} from '../../services/app.idea';
import {UserService} from '../../services/app.user';
//import {NgxMasonryComponent} from 'ngx-masonry';
import {BaThemeSpinner}  from '../../theme/services';
import {Utility} from '../../services/app.utility';
import {UserProfile} from '../shared/profile/profile.component';
import {Abuse} from '../shared/abuse/abuse.component';
import {Ideas} from '../shared/ideas/idea.component';
import {Constants} from '../../../app/common/app.constants';
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'Listidea',
    encapsulation: ViewEncapsulation.None,
    templateUrl: './listidea.html',
    styleUrls: ['./listidea.scss']
})


export class Listidea {
    @Input()
    constants:Constants;
    @ViewChild(UserProfile)
    profile:UserProfile;
    @ViewChild('abuseModal')
    public Abuse:Abuse;
    // @ViewChild('myMasonry')
    // private myMasonry:NgxMasonryComponent;
    @ViewChild('ideas')
    public getAllIdeaCard:Ideas;
    myDatePickerOptions:any;
    fromDate:string;
    toDate:string;
    public versioning:boolean;
    TotalIdeas:any[];
    public optionstags:any;
    public Ideas_Page:any;
    public Categories:any;
    public start:any;
    public end:any;
    public date:any;
    public check:any;
    public downIcon:any;
    public category:any;
    public inTags:any;
    public showMoreIdeaButton:any;
    public noMoreContent:any;
    public upIcon:any;
    public alphabet:any;
    public points:any;
    public like:any;
    public comment:any;
    public categoriesList:any;
    public allTags:any;

    constructor(private userService:UserService, private ideaService:IdeaService, private spinner:BaThemeSpinner, public utility:Utility) {
        this.constants = new Constants();
        this.versioning = false;
        this.start = 0;
        this.check = 0;

        // Function for start timeline count
        this.startCount();

        this.optionstags = {
            placeholder: "Search by Tags",
            secondaryPlaceholder: "Search by Tags",
        };
        let todayDate = new Date();
        this.myDatePickerOptions = {
            todayBtnTxt: 'Today',
            dateFormat: 'dd/mm/yyyy',
            firstDayOfWeek: 'mo',
            sunHighlight: true,
            height: '34px',
            width: '260px',
            inline: false,
            disableSince: {
                year: todayDate.getFullYear(),
                month: todayDate.getUTCMonth() + 1, day: todayDate.getDate() + 1
            },
            selectionTxtFontSize: '16px'
        };
        this.date = true;
        this.downIcon = true;
        this.category = 'Tags';
        this.inTags = [];

        // Set from and to date to date picker in DD/MM/YYYY format
        this.fromDate = utility.getDatewithoutTimstamp(utility.getXMonthsAgoDate(new Date(), 180));
        this.toDate = utility.getDatewithoutTimstamp(new Date());

        let fromDate:any;
        fromDate = this.fromDate.split("/");
        //from month
        if (fromDate[0] < 10) {
            fromDate[0] = 0 + '' + fromDate[0];
        }
        //from day
        if (fromDate[1] < 10) {
            fromDate[1] = 0 + '' + fromDate[1];
        }
        this.fromDate = fromDate[1] + '/' + fromDate[0] + '/' + fromDate[2];

        //to month
        let toDate:any;
        toDate = this.toDate.split("/");
        if (toDate[0] < 10) {
            toDate[0] = 0 + '' + toDate[0];
        }

        //to day
        if (toDate[1] < 10) {
            toDate[1] = 0 + '' + toDate[1];
        }
        this.toDate = toDate[1] + '/' + toDate[0] + '/' + toDate[2];

        this.Ideas_Page = {
            skipItem: 0,
            itemsperPage: 6,
            sortParameter: 'createdAt',
            sortOrder: 'descending',
            sortByTitle: '',
            sortByAuthor: '',
            sortByTags: [],
            toDate: this.toDate,
            fromDate: this.fromDate

        };

        // function for get save tags
       var that = this
      setTimeout(function () {
        that.getTags();
      }, 3000)



        // API call for get user info
        this.userService.getuserInfo().subscribe(
            data => this.userInfoSuccess(data),
            error => {
            }
        );
    }


    //Convert Date to MM/DD/YY
    public formateDate(dates):any {
        return this.utility.getFormattedDate(dates);
    }
  deleteIdea(){
    this.Ideas_Page.itemsperPage = this.Ideas_Page.skipItem + 6;
    this.Ideas_Page.skipItem = 0;
    this.ideaLists();
  }
    //Function for fetching List of Ideas
    public ideaLists() {
        this.spinner.showProgress();
        this.Ideas_Page.toDate = this.toDate;
        this.Ideas_Page.fromDate = this.fromDate;
        this.ideaService.ideaList(this.Ideas_Page).subscribe(
            data => this.fetchListOfIdeasuccess(data),
            error => this.fail(error)
        );
    }

    // Function for fail to load listidea
    public fail(error) {
        this.spinner.hideProgress();
    }

    // Function call when user info got successfully
    public userInfoSuccess(data) {
      console.log("invoke ");



        if (data.version === 'Version_1') {
            this.versioning = false;
        } else if (data.version === 'Version_2') {
            this.versioning = false;
        } else if (data.version === 'Version_4') {
            this.versioning = false;
        } else if (data.version === 'Version_6') {
            this.versioning = false;
        } else {
            this.versioning = true;
        }
    }

    // Function call after view load and call list of idea
    ngAfterViewInit() {
        this.ideaLists();
    }

    // Function get list of idea successfully
    public fetchListOfIdeasuccess(result) {
        if (this.versioning) {
            for (let x = 0; x < result.ideaList.length; x++) {
                if (result.ideaList[x].citationArray !== undefined) {
                    for (let y = 0; y < result.ideaList[x].citationArray.length; y++) {
                        result.ideaList[x].content = result.ideaList[x].content.replace(result.ideaList[x].citationArray[y], '<span class="keywordColor">' + result.ideaList[x].citationArray[y] + '</span>');
                    }
                }
            }
        }

        this.spinner.hideProgress();

        if (this.Ideas_Page.skipItem != 0) {
            let setData:any;
            setData = this.TotalIdeas;
            setData.ideaList = setData.ideaList.concat(result.ideaList);
            this.TotalIdeas = null;
            this.TotalIdeas = setData;
        }
        else {
            this.TotalIdeas = result;
            this.Ideas_Page.skipItem = this.Ideas_Page.itemsperPage - 6;
            this.Ideas_Page.itemsperPage = 6;
        }
        this.getAllIdeaCard.setIdeasInMasonry(this.TotalIdeas);
        if ((result.ideaCount - this.Ideas_Page.skipItem) > this.Ideas_Page.itemsperPage) {
            this.showMoreIdeaButton = true;
        }
        else {
            this.showMoreIdeaButton = false;
        }
        this.noMoreContent = (result.ideaCount > 0) ? false : true;
    }

    // Function for set filters icon active and unactive
    public ideaListFilter(filter) {
        this.Ideas_Page.sortOrder = 'descending';
        if (filter === 'dates') {
            this.downIcon = true;
            this.upIcon = false;
            this.date = true;
            this.alphabet = false;
            this.like = false;
            this.points = false;
            this.comment = false;
            this.Ideas_Page.sortParameter = 'createdAt';

        }
        else if (filter === 'likes') {
            this.upIcon = false;
            this.downIcon = true;
            this.date = false;
            this.alphabet = false;
            this.like = true;
            this.points = false;
            this.comment = false;
            this.Ideas_Page.sortParameter = 'likes';
        }
        else if (filter === 'comment') {
            this.upIcon = false;
            this.downIcon = true;
            this.date = false;
            this.like = false;
            this.points = false;
            this.alphabet = false;
            this.comment = true;
            this.Ideas_Page.sortParameter = 'commentCount';
        }
        else if (filter === 'points') {
            this.upIcon = false;
            this.downIcon = true;
            this.date = false;
            this.like = false;
            this.points = true;
            this.comment = false;
            this.alphabet = false;
            this.Ideas_Page.sortParameter = 'points';
        }
        else if (filter === 'alphabet') {
            this.upIcon = false;
            this.downIcon = true;
            this.alphabet = true;
            this.date = false;
            this.like = false;
            this.points = false;
            this.comment = false;
            this.Ideas_Page.sortParameter = 'title';
            this.Ideas_Page.sortOrder = 'ascending';
        }

        this.Ideas_Page.skipItem = 0;
        this.ideaLists();

    }

    //Up and Down arraow for Searching based on filter
    public filterResult(filter) {
        if (this.Ideas_Page.sortOrder != filter) {
            this.Ideas_Page.sortOrder = filter;
            this.Ideas_Page.skipItem = 0;
            this.ideaLists();
        }
    }

    //Showing button for more card "SEE More"
    public showMoreIdea() {
        this.Ideas_Page.skipItem += this.Ideas_Page.itemsperPage;
        this.ideaLists();
    }

    // Added for title auto dropdown
    public getIdeaCategory(category) {
        category = category.trim();
        if (category.length > 0) {
            if (this.category == 'Title') {
                let data = {
                    title: this.Categories
                };
                this.ideaService.getIdea(data).subscribe(
                    data => this.getIdeaCategoriesSucces(data),
                    error => {
                    });
            }
            if (this.category == 'Author') {
                let data = {
                    author: this.Categories
                };
                this.userService.getideabyAuthor(data).subscribe(
                    data=> this.getIdeaCategoriesSucces(data),
                    error => {
                    });
            }
        }
        else {
            this.categoriesList = [];
        }
    }

    // Function for get category successfully from API
    private getIdeaCategoriesSucces(data) {
        this.categoriesList = data;
    }

    // Function for change From date of Datepicker
    onFromDateChanged(event:any) {
        if (event.formatted === '') {

        } else {
            let day, month;
            day = event.date.day;
            month = event.date.month;
            if (event.date.month < 10) {
                month = 0 + '' + event.date.month;
            }
            if (event.date.day < 10) {
                day = 0 + '' + event.date.day;
            }

            this.fromDate = day + '/' + month + '/' + event.date.year;
        }
    }


    // Fuction for change To date of datepicker
    onToDateChanged(event:any) {
        if (event.formatted === '') {

        } else {
            let day, month;
            day = event.date.day;
            month = event.date.month;
            if (event.date.month < 10) {
                month = 0 + '' + event.date.month;
            }
            if (event.date.day < 10) {
                day = 0 + '' + event.date.day;
            }

            this.toDate = day + '/' + month + '/' + event.date.year;
        }
    }


    //Get List of All Tags
    getTags() {
        let input = {
            tags: ''
        };
        this.ideaService.searchTags(input).subscribe(
            data => this.tagsSerchSuccess(data[0]),
            error => {
            }
        );



    }

    // Successfully found tags and pass to view
    tagsSerchSuccess(result) {
        this.allTags = result.tags;
    }

    // Function for set search content based on title, author and tag
    public getListOfIdea() {

        this.Ideas_Page.skipItem = 0;
        if (this.category == 'Title') {
            this.Ideas_Page.sortByTitle = this.Categories;
            this.Ideas_Page.sortByAuthor = '';
            this.Ideas_Page.sortByTags = [];
        }
        else if (this.category === 'Author') {
            this.Ideas_Page.sortByTitle = '';
            this.Ideas_Page.sortByAuthor = this.Categories;
            this.Ideas_Page.sortByTags = [];
        }
        else if (this.category === 'Tags') {
            this.Ideas_Page.sortByTitle = '';
            this.Ideas_Page.sortByAuthor = '';
            this.Ideas_Page.sortByTags = [];
            this.inTags.map(item => this.Ideas_Page.sortByTags.push(item.value));
        }
        this.ideaLists();
    }

    // Function for set user log on keystroke
    public onSearchIdea(event) {
        let input = {
            'target': 'HTMLInputElement : ' + event.code + ' listidea seach',
            'value': 'listidea search',
            'action': 'keystroke'
        };
        this.userService.setUserLogs(input).subscribe();
    }

    // To call every 1 sec for count how much time we spent on this page
    public  timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();

      // API call for tract navigation sequence
      let seq = {
        sequence: {
          "pageName": 'listIdea',
          "timeSpent": this.start
        }

      };
      this.userService.setUrlSeq(seq).subscribe();

    }

    // Function call after view for log API
    ngAfterViewChecked() {
        let self = this;
        $('#listIdeaLog').unbind().mousedown(function (event) {
            self.checkAllLogs(event);
        });
    }

    // Function for check all logs
    public checkAllLogs(event) {
        let self = this;
        let buttons;
        if (event.button === 0) {
            buttons = 'left click';
        } else if (event.button === 1) {
            buttons = 'roller click';
        } else {
            buttons = 'right click';
        }
        let domTarget = event.target;
        let domTargetString = domTarget.toString();
        let stringDemo = domTargetString.substr(12, 25);
        let index = stringDemo.indexOf('E');
        let dom = stringDemo.substr(0, index);
        let text = $(event.target).unbind().text();


        let input = {
            'target': dom + ' ' + text,
            'value': text,
            'action': buttons
        };

        if (event.target.className.indexOf('ion-thumbsup') >= 0) {
            let input = {
                'target': 'Like',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-thumbsdown') >= 0) {
            let input = {
                'target': 'Dislike',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-android-star') >= 0) {
            let input = {
                'target': 'Points',
                'value': '',
                'action': buttons
            };
            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-heart') >= 0) {
            let input = {
                'target': 'Favourite',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-chatboxes') >= 0) {
            let input = {
                'target': 'Comment',
                'value': '',
                'action': buttons
            };
            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-alert-circled') >= 0) {
            let input = {
                'target': 'Abuse',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (text.indexOf('×') >= 0) {
            let input = {
                'target': 'Closed modal',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ion-edit') >= 0) {
            let data = {
                'target': this.constants.URL + 'admin/edituser',
                'value': 'admin/edituser',
                'action': 'redirect'
            };

            self.userService.setUserLogs(data).subscribe();
        } else {
            self.setUserLogs(input);
        }
    }

    // Function for call API for log
    public setUserLogs(input) {
        this.userService.setUserLogs(input).subscribe();
    }


}
